﻿using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using YiDa.Infrastructure;
using Microsoft.Practices.Unity.InterceptionExtension;
using System.Collections.Generic;
using YiDa.Infrastructure.Caching;

namespace YiDa.Infrastructure.Test
{
    [TestClass]
    public class ServiceLocatorTest
    {
        [TestMethod]
        public void TestGetService()
        {
            var obj = ServiceLocator.Instance.GetService<IUnitOfWork>();
            Assert.IsNotNull(obj);
            
            //Intercept.ThroughProxy<IUnitOfWork>(obj,new InterfaceInterceptor())
        }

        [TestMethod]
        public void TestCachingBehaviors()
        {
            var obj = ServiceLocator.Instance.GetService<IAOPTester>();

            String p = "1,2,3,4";
            
            var r1 = obj.GetList(p);
            var r2 = obj.GetList(p);
            Assert.AreEqual(true, r1 == r2);
        }

        [TestMethod]
        public void TestExceptionBehaviors()
        {
            var obj = ServiceLocator.Instance.GetService<IAOPTester>();

            try
            {
                obj.Create();           //只为了检查异常拦截器是否起了作用,需要检查日志文件
            }
            catch (NotImplementedException e)
            {
                //do nothing
            }
        }

        [TestMethod]
        public void TestPerRequestLifetimeManager()
        {
            var obj = ServiceLocator.Instance.GetService<IAOPTester>();
            var obj1 = ServiceLocator.Instance.GetService<IAOPTester>();
            Assert.IsNotNull(obj);
            Assert.IsNotNull(obj1);
            if (obj.GetType().ToString().StartsWith("DynamicModule.ns.Wrapped"))
            {
                Assert.AreEqual(true, obj.ToString() == obj1.ToString());         //如果是被拦截器生成的动态代理,则使用ToString()进行比较
            }
            else
            {
                Assert.AreEqual(true, obj == obj1);                                 //测试WcfPerRequestLifetimeManager
            }               
        }
    }

    public class UnitOfWork:IUnitOfWork
    {
        public bool Committed
        {
            get { throw new NotImplementedException(); }
        }

        public void Commit()
        {
            throw new NotImplementedException();
        }

        public void Rollback()
        {
            throw new NotImplementedException();
        }
    }

    public interface IAOPTester
    {
        [Caching(CachingMethod.Get)]
        List<string> GetList(string v);

        void Create();
    }

    public class AOPTester : IAOPTester
    {
        public List<string> GetList(string v)
        {
            var a = v.Split(',');
            List<string> l = new List<string>();
            l.AddRange(a);
            return l;
        }

        public void Create()
        {
            throw new NotImplementedException();
        }
    }
}
